After about an hour of pounding my head over how I can automatically encode a stored password after it has been modified I came up with what I think is a pretty clever solution (though hopefully not the best, let me know if you know a better one that doesn't involve stored procedures!):
@Entity
public class Member {
Integer id;
String username;
String password;
...
transient boolean hasPasswordChanged;
@PrePersist void beforeInsert() {
if( hasPasswordChanged ) {
password = encode( password );
hasPasswordChanged = false;
}
}
public void setPassword(String password) {
hasPasswordChanged = true;
this.password = password;
}
...
}
The function tagged with the PrePersist annotation is called before the entity manager persists an entity to the data source. This is the ideal time to perform operations like this. The 'transient' field simply means that the value will not be serialized or persisted to the database.